package com.yupi.yupao.websocket;

import com.yupi.yupao.common.BaseContext;
import com.yupi.yupao.model.domain.Invitation;
import com.yupi.yupao.service.TeamService;
import com.yupi.yupao.websocket.client.WebSocketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket服务
 */
@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebSocketServer {
    static final ConcurrentHashMap<String, List<WebSocketClient>> webSocketClientMap = new ConcurrentHashMap<>();

    //存放会话对象
    private static Map<String, Session> sessionMap = new HashMap();
    @Resource
    private TeamService teamService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
//        String userId = (String) session.getUserProperties().get("userId");
//        System.out.println("用户：" + userId + " 连接成功");
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);


    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端：" + sid + "的信息:" + message);
    }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 单发
     *
     * @param sid     目标用户的sid
     * @param message 发送的消息
     */
    public void sendToClient(String sid, String message) {
        Session session = sessionMap.get(sid);
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
                log.info("用户信息" + message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("用户未连接或不存在: " + sid);
        }
    }

    // 检查用户是否已连接
    public boolean isUserConnected(String sid) {
        Session session = sessionMap.get(sid);
        return session != null && session.isOpen();
    }

}
